<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue'
import AddPost from '../post/AddPost.vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { User, SwitchButton, Message } from '@element-plus/icons-vue'
import axios from 'axios'
import { ElMessage } from "element-plus";

const srk = ref('')
const userStore = useUserStore()
const yhm = userStore.yhm;
console.log(yhm);
const isLoggedIn = ref(userStore.isLoggedIn);
const handleSelect = (key: string, keyPath: string[]) => {
  console.log(key, keyPath)
}
const router = useRouter()
const addDialogVisible = ref(false);
const showAdd = () => {
  if (isLoggedIn.value) {
    addDialogVisible.value = true;
  } else {
    router.push('/login');
  }
}
const tcdl = () => {
  userStore.clearUserName()
  userStore.clearUserId()
  window.location.reload();
}
import {
  Search,
  HomeFilled,
  Star,
  VideoPlay,
  MoreFilled,
  Setting,
  CirclePlus
} from '@element-plus/icons-vue'
const tx = ref('https://tvax1.sinaimg.cn/crop.0.0.1080.1080.180/0086eF7Vly8h6lg9cm5wnj30u00u0ab8.jpg?KID=imgbed,tva&Expires=1752993846&ssig=Y8W%2FvmEB%2F2')

const handleSearch = () => {
  if(srk.value===''){
    ElMessage.error('请输入搜索内容')
    return
  }
  router.push(`/search?srk=${srk.value}`)
}

// 存储通知数量的变量
const noticeCount = ref(0)

// 获取未读通知数量的函数
const getUnreadNoticeCount = async () => {
  try {
    if (isLoggedIn.value) {
      const userId = userStore.id
      const { data } = await axios.get('/api/notice/unread-count', { params: { userId } })
      noticeCount.value = data.count || 0
      console.log('未读通知数量:', noticeCount.value)
    } else {
      noticeCount.value = 0
    }
  } catch (error) {
    ElMessage.error('获取通知数量失败，请稍后重试')
    console.error('获取通知数量失败:', error)
  }
}

// 标记所有通知为已读
const markAllAsRead = async () => {
  try {
    if (isLoggedIn.value) {
      const userId = userStore.id
      await axios.put(`/api/notice/mark-all-read`, { userId })
      noticeCount.value = 0 // 立即清除红点
      console.log('所有通知已标记为已读')
    }
  } catch (error) {
    console.error('标记所有通知为已读失败:', error)
  }
}

// 点击消息图标处理函数
const handleNoticeClick = async () => {
  if (isLoggedIn.value) {
    // 仅跳转到通知页面，不再自动标记所有为已读
    router.push('/notice')
  } else {
    router.push('/login')
  }
}

// 监听路由变化，当从其他页面返回时检查新消息
watch(() => router.currentRoute.value.path, async (newPath) => {
  // 非通知页面且用户已登录时，检查是否有新消息
  if (newPath !== '/notice' && isLoggedIn.value) {
    await getUnreadNoticeCount()
  }
})

// 定时检查新消息（每30秒一次）
const checkNewNotices = async () => {
  if (isLoggedIn.value && router.currentRoute.value.path !== '/notice') {
    await getUnreadNoticeCount()
  }
}

// 组件挂载时初始化
onMounted(() => {
  getUnreadNoticeCount()
  // 设置定时检查新消息
  const interval = setInterval(checkNewNotices, 30000) // 30秒检查一次
  // 组件卸载时清除定时器
  return () => clearInterval(interval)
})
</script>

<template>

  <div class="navbar-container">
    <el-row class="navbar" justify="space-between" align="middle">
      <!-- 左侧部分 -->
      <el-col :span="4" class="left-section">
        <div class="logo-area">
          <el-icon size="24" color="red">
            <!-- 这里放微博图标，实际项目中替换为微博图标组件 -->
            <component :is="'el-icon-platform-eleme'" />
          </el-icon>
          <span class="logo-text">博客</span>
        </div>
      </el-col>

      <!-- 中间部分 -->
      <el-col :span="12" class="center-section">
        <el-input
            class="search-input"
            placeholder="搜索博客"
            :prefix-icon="Search"
            v-model="srk"
            @keyup.enter="handleSearch"
        />
        <el-button @click="handleSearch" >搜索</el-button>
      </el-col>

      <!-- 右侧部分 -->
      <el-col :span="8" class="right-section">
        <div class="nav-items">
          <el-button class="bu" v-if="isLoggedIn">
            <span>{{yhm}}</span>
            <el-avatar :size="32" :src="tx" />
          </el-button>
          <el-button class="bu" @click="router.push('/login')" v-if="!isLoggedIn">
            <span class="nav-items-text">登录</span>
          </el-button>
          <el-button class="bu" @click="router.push('/yycsh/sign')" v-if="!isLoggedIn">
            <span class="nav-items-text">注册</span>
          </el-button>
          <!--          <el-button class="bu">-->
          <!--            <el-icon class="nav-items-icon"><Setting /></el-icon>-->
          <!--          </el-button>-->
          <el-dropdown v-if="isLoggedIn" trigger="click" placement="bottom-end">
            <el-button class="bu">
              <el-icon class="nav-items-icon"><Setting /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="router.push(
                    {
                        path: '/hoet',
                        query: {
                            id: userStore.id
                        }
                    }
                )">
                  <el-icon><User /></el-icon>
                  <span style="margin-left: 8px">个人信息</span>
                </el-dropdown-item>
                <el-dropdown-item divided @click="tcdl">
                  <el-icon><SwitchButton /></el-icon>
                  <span style="margin-left: 8px">退出登录</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>

          <el-button v-else class="bu">
            <el-icon class="nav-items-icon"><Setting /></el-icon>
          </el-button>
          <el-button class="bu" @click="router.push('/mychat')">
            <el-icon  class="nav-items-icon" ><Message /></el-icon>
            <span class="nav-items-text">去私信</span>
          </el-button>
          <el-button class="bu"  @click="showAdd">
            <el-icon class="nav-items-icon"><CirclePlus /></el-icon>
            <span class="nav-items-text">发贴子</span>
          </el-button>
          <el-button class="bu" @click="router.push('/')">
            <el-icon class="nav-items-icon"><HomeFilled /></el-icon>
            <span class="nav-items-text">首页</span>
          </el-button>

<!--          <el-button  class="bu">-->
<!--            <el-icon class="nav-items-icon"><Star /></el-icon>-->
<!--            <span class="nav-items-text">热门</span>-->
<!--          </el-button>-->

          <el-button class="bu" @click="router.push('/video')">
            <el-icon class="nav-items-icon"><VideoPlay /></el-icon>
            <span class="nav-items-text">视频</span>
          </el-button>

          <el-button class="bu" @click="handleNoticeClick">
            <el-badge :value="noticeCount" :max="99" :hidden="noticeCount <= 0">
              <el-icon class="nav-items-icon"><Message /></el-icon>
            </el-badge>
          </el-button>




        </div>
      </el-col>
    </el-row>
  </div>
  <!-- 发布博客 dialog-->
  <el-dialog v-model="addDialogVisible"  width="40%" top="2vh" destroy-on-close>
    <add-post   @closeDialog="addDialogVisible = false">

    </add-post>
  </el-dialog>
</template>

<style scoped>
.navbar-container {
  width: 100%;
  height: 60px;
  background-color: white;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  position: fixed; /* 关键修改：固定定位 */
  top: 0; /* 固定在顶部 */
  left: 0; /* 从左侧开始 */
}

.navbar {
  height: 100%;
  padding: 0 20px;
}

.left-section {
  display: flex;
  align-items: center;
}
.bu{
  border: none;
}
.logo-area {
  display: flex;
  align-items: center;
  gap: 8px;
}

.logo-text {
  font-weight: bold;
  font-size: 25px;
}

.domain {
  color: #999;
  font-size: 14px;
}

.center-section {
  display: flex;
  justify-content: center;
}

.search-input {
  width: 50%;
}

.right-section {
  display: flex;
  justify-content: flex-end;
}

.nav-items {
  display: flex;
  align-items: center;
  gap: 10px;
}
.nav-items-icon {
  font-size: 22px; /* 增大图标大小 */
  margin-bottom: 2px;
}

.nav-items-text {
  font-size: 14px; /* 增大文字大小 */
  color: #333;
}
.accessibility-btn {
  color: #666;
}
</style>